<template>
  <div class="bazi-section">
    <div class="bazi-table-container">
      <table class="bazi-table">
        <thead>
          <tr>
            <th v-if="showLabelColumn" class="table-label">日期</th>
            <th 
              v-for="column in columns" 
              :key="column.key"
              class="table-label"
            >
              {{ column.label }}
            </th>
          </tr>
        </thead>
        <tbody>
          <!-- 主星 -->
          <tr class="table-row">
            <td v-if="showLabelColumn" class="table-label">主星</td>
            <td 
              v-for="column in columns" 
              :key="column.key"
              class="table-cell"
            >
              {{ getTenStar(column.key) }}
            </td>
          </tr>

          <!-- 天干 -->
          <tr class="table-row">
            <td v-if="showLabelColumn" class="table-label">天干</td>
            <td 
              v-for="column in columns" 
              :key="column.key"
              class="table-cell stem-cell"
            >
              <template v-if="getPillar(column.key)?.stem">
                <span 
                  class="ganzhi-text" 
                  :style="{ color: getTianganColor(getPillar(column.key)!.stem!) }"
                >
                  {{ getPillar(column.key)?.stem }}
                </span>
              </template>
            </td>
          </tr>

          <!-- 地支 -->
          <tr class="table-row">
            <td v-if="showLabelColumn" class="table-label">地支</td>
            <td 
              v-for="column in columns" 
              :key="column.key"
              class="table-cell branch-cell"
            >
              <template v-if="getPillar(column.key)?.branch">
                <span 
                  class="ganzhi-text" 
                  :style="{ color: getDizhiColor(getPillar(column.key)!.branch!) }"
                >
                  {{ getPillar(column.key)?.branch }}
                </span>
              </template>
            </td>
          </tr>

          <!-- 藏干 -->
          <tr class="table-row">
            <td v-if="showLabelColumn" class="table-label">藏干</td>
            <td 
              v-for="column in columns" 
              :key="column.key"
              class="table-cell zanggan-cell"
            >
              <div v-if="getPillar(column.key)?.zanggan && getPillar(column.key)!.zanggan!.length > 0">
                <div 
                  v-for="zang in getPillar(column.key)!.zanggan" 
                  :key="zang.stem + (zang.type || '')"
                  class="zanggan-item"
                  :style="{ color: getTianganColor(zang.stem) }"
                >
                  {{ zang.stem }}{{ getWuxing(zang.stem) || '' }}
                </div>
              </div>
            </td>
          </tr>

          <!-- 副星 -->
          <tr class="table-row">
            <td v-if="showLabelColumn" class="table-label">副星</td>
            <td 
              v-for="column in columns" 
              :key="column.key"
              class="table-cell zanggan-cell"
            >
              <div v-if="getPillar(column.key)?.zanggan && getPillar(column.key)!.zanggan!.length > 0">
                <div 
                  v-for="zang in getPillar(column.key)!.zanggan" 
                  :key="zang.stem + (zang.type || '')"
                  class="zanggan-item"
                >
                  {{ zang.tenStar || '' }}
                </div>
              </div>
            </td>
          </tr>



                 <!-- 星运 -->
                 <tr class="table-row">
            <td v-if="showLabelColumn" class="table-label">星运</td>
            <td 
              v-for="column in columns" 
              :key="column.key"
              class="table-cell"
            >
              {{ getPillar(column.key)?.xingyun }}
            </td>
          </tr>
          <!-- 自坐 -->
          <tr class="table-row">
            <td v-if="showLabelColumn" class="table-label">自坐</td>
            <td 
              v-for="column in columns" 
              :key="column.key"
              class="table-cell"
            >
              {{ getPillar(column.key)?.zizuo }}
            </td>
          </tr>

             

          <!-- 空亡 -->
          <tr class="table-row">
            <td v-if="showLabelColumn" class="table-label">空亡</td>
            <td 
              v-for="column in columns" 
              :key="column.key"
              class="table-cell"
            >
              {{ getPillar(column.key)?.kongwang }}
            </td>
          </tr>

                    <!-- 纳音 -->
                    <tr class="table-row">
            <td v-if="showLabelColumn" class="table-label">纳音</td>
            <td 
              v-for="column in columns" 
              :key="column.key"
              class="table-cell"
            >
              {{ getPillar(column.key)?.nayin }}
            </td>
          </tr>

          <!-- 神煞 -->
          <tr class="table-row">
            <td v-if="showLabelColumn" class="table-label">神煞</td>
            <td 
              v-for="column in columns" 
              :key="column.key"
              class="table-cell shenshas-cell"
            >
              <div v-if="getPillar(column.key)?.shenshas && getPillar(column.key)!.shenshas!.length > 0">
                <div 
                  v-for="shensha in getPillar(column.key)!.shenshas" 
                  :key="shensha"
                  class="shensha-item"
                >
                  {{ shensha }}
                </div>
              </div>
            </td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed } from 'vue'
import { getTianganColor, getDizhiColor, getWuxing } from '@/utils/wuxing'

interface Zanggan {
  stem: string
  type?: string
  tenStar?: string
}

interface TenStar {
  heavenStem?: string
  heavenStemShort?: string
  earthBranch?: string
  earthBranchShort?: string
}

interface Pillar {
  stem?: string
  branch?: string
  tenStar?: string | TenStar
  zanggan?: Zanggan[]
  nayin?: string
  zizuo?: string
  xingyun?: string
  kongwang?: string
  shenshas?: string[]
}

interface BaziData {
  year?: Pillar
  month?: Pillar
  day?: Pillar
  hour?: Pillar
  shengong?: Pillar
  minggong?: Pillar
  taiyuan?: Pillar
  decade?: Pillar // 大运
  fortune?: Pillar // 流年
  monthTime?: Pillar // 流月
  dayTime?: Pillar // 流日
  hourTime?: Pillar // 流时
}

interface Props {
  baziData?: BaziData
  showTaiMingShen?: boolean // 是否显示胎命身
  showLabelColumn?: boolean // 是否显示左侧标签列
  // 时间模式数据（与 showTaiMingShen 互斥）
  decade?: Pillar // 大运
  fortune?: Pillar // 流年
  monthTime?: Pillar // 流月
  dayTime?: Pillar // 流日
  hourTime?: Pillar // 流时
  isXiaoyun?: boolean // 是否是小运（第一个大运且 xiaoyun: true）
}

const props = withDefaults(defineProps<Props>(), {
  showTaiMingShen: false,
  showLabelColumn: true // 默认显示左侧标签列
})

// 检查是否有时间模式数据
const hasTimeMode = computed(() => {
  return !!(props.decade || props.fortune || props.monthTime || props.dayTime || props.hourTime)
})

// 定义列配置
const columns = computed(() => {
  const baseColumns = [
    { key: 'year', label: '年柱' },
    { key: 'month', label: '月柱' },
    { key: 'day', label: '日柱' },
    { key: 'hour', label: '时柱' }
  ]
  
  // 时间模式和胎命身模式互斥，优先显示时间模式
  if (hasTimeMode.value) {
    // 根据传递的数据动态生成列，确保连贯性
    // 顺序：流时 -> 流日 -> 流月 -> 流年 -> 大运 -> 年柱...
    const timeColumns: Array<{ key: string; label: string }> = []
    
    // 从最细粒度到最粗粒度：流时 -> 流日 -> 流月 -> 流年 -> 大运
    if (props.hourTime) {
      // 如果传递流时，必须传递前面的所有数据
      timeColumns.push({ key: 'hourTime', label: '流时' })
      if (props.dayTime) timeColumns.push({ key: 'dayTime', label: '流日' })
      if (props.monthTime) timeColumns.push({ key: 'monthTime', label: '流月' })
      if (props.fortune) timeColumns.push({ key: 'fortune', label: '流年' })
      if (props.decade) {
        const decadeLabel = props.isXiaoyun ? '小运' : '大运'
        timeColumns.push({ key: 'decade', label: decadeLabel })
      }
    } else if (props.dayTime) {
      // 如果传递流日，必须传递大运、流年、流月
      timeColumns.push({ key: 'dayTime', label: '流日' })
      if (props.monthTime) timeColumns.push({ key: 'monthTime', label: '流月' })
      if (props.fortune) timeColumns.push({ key: 'fortune', label: '流年' })
      if (props.decade) {
        const decadeLabel = props.isXiaoyun ? '小运' : '大运'
        timeColumns.push({ key: 'decade', label: decadeLabel })
      }
    } else if (props.monthTime) {
      // 如果传递流月，必须传递大运、流年
      timeColumns.push({ key: 'monthTime', label: '流月' })
      if (props.fortune) timeColumns.push({ key: 'fortune', label: '流年' })
      if (props.decade) {
        const decadeLabel = props.isXiaoyun ? '小运' : '大运'
        timeColumns.push({ key: 'decade', label: decadeLabel })
      }
    } else if (props.fortune) {
      // 如果传递流年，必须传递大运
      timeColumns.push({ key: 'fortune', label: '流年' })
      if (props.decade) {
        const decadeLabel = props.isXiaoyun ? '小运' : '大运'
        timeColumns.push({ key: 'decade', label: decadeLabel })
      }
    } else if (props.decade) {
      // 如果只传递大运，根据 isXiaoyun 显示"小运"或"大运"
      const decadeLabel = props.isXiaoyun ? '小运' : '大运'
      timeColumns.push({ key: 'decade', label: decadeLabel })
    }
    
    return [...timeColumns, ...baseColumns]
  }
  
  // 如果没有时间模式，才显示胎命身模式
  if (props.showTaiMingShen) {
    return [
      { key: 'shengong', label: '身宫' },
      { key: 'minggong', label: '命宫' },
      { key: 'taiyuan', label: '胎元' },
      ...baseColumns
    ]
  }
  
  return baseColumns
})

// 获取指定柱的数据
const getPillar = (key: string): Pillar | undefined => {
  // 优先从时间模式 props 中获取
  if (key === 'decade' && props.decade) return props.decade
  if (key === 'fortune' && props.fortune) return props.fortune
  if (key === 'monthTime' && props.monthTime) return props.monthTime
  if (key === 'dayTime' && props.dayTime) return props.dayTime
  if (key === 'hourTime' && props.hourTime) return props.hourTime
  
  // 从 baziData 中获取
  if (props.baziData) {
    return props.baziData[key as keyof BaziData] as Pillar | undefined
  }
  
  return undefined
}

// 获取十神（完整名称，不使用缩写）
const getTenStar = (key: string): string => {
  const pillar = getPillar(key)
  if (!pillar || !pillar.tenStar) return ''
  
  // 如果是对象，取 heavenStem（完整名称）
  if (typeof pillar.tenStar === 'object') {
    const tenStarObj = pillar.tenStar as TenStar
    return tenStarObj.heavenStem || ''
  }
  
  // 如果是字符串，直接返回
  if (typeof pillar.tenStar === 'string') {
    return pillar.tenStar
  }
  
  return ''
}
</script>

<style scoped>
.bazi-section {
  margin-bottom: 16px;
}

.bazi-table-container {
  width: 100%;
  overflow-x: auto;
  -webkit-overflow-scrolling: touch;
}

.bazi-table {
  width: 100%;
  border-collapse: collapse;
  font-size: 16px;
  background: transparent;
  table-layout: auto;
}

.table-header {
  background: transparent;
  color: #888888;
  font-weight: 600;
  padding: 12px 8px;
  text-align: center;
  font-size: 15px;
}

.table-row:nth-child(odd) {
  background: #f8fafc;
}

.table-row:nth-child(even) {
  background: transparent;
}

/* 标签部分（写死的文字）：使用灰色 */
.table-label {
  background: transparent;
  color: #888888;
  font-weight: 600;
  padding: 8px 4px;
  text-align: center;
  font-size: 14px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  word-break: break-all;
}

/* 数据部分（接口返回的字段）：使用黑色 */
.table-cell {
  padding: 8px 4px;
  text-align: center;
  color: #4d4d4d;
  font-weight: 500;
  vertical-align: middle;
  font-size: 14px;
  white-space: normal;
  word-break: break-word;
  overflow: hidden;
}

.ganzhi-cell {
  font-size: 18px;
  font-weight: 700;
  color: #4d4d4d;
  background: linear-gradient(135deg, #3b82f6, #1d4ed8);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.stem-cell {
  font-size: clamp(18px, 4vw, 24px);
  font-weight: 700;
}

.branch-cell {
  font-size: clamp(18px, 4vw, 24px);
  font-weight: 700;
}

.ganzhi-text {
  font-size: clamp(28px, 4vw, 24px);
  font-weight: 700;
  line-height: 1;
  display: inline-block;
}

.zanggan-cell {
  text-align: center;
  vertical-align: top;
  padding: 4px 2px;
}

.zanggan-item {
  font-size: clamp(12px, 2.5vw, 14px);
  color: #4d4d4d;
  margin-bottom: 2px;
  line-height: 1.3;
  text-align: center;
  word-break: break-word;
}

.shenshas-cell {
  text-align: center;
  vertical-align: top;
  padding: 4px 2px;
}

.shensha-item {
  font-size: clamp(12px, 2.5vw, 14px);
  color: #4d4d4d;
  margin-bottom: 2px;
  line-height: 1.3;
  text-align: center;
  word-break: break-word;
}
</style>
